package threadDemo;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReenTrantReadWriteLockDemo {
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    public static void main(String[] args) {
        final ReenTrantReadWriteLockDemo test = new ReenTrantReadWriteLockDemo();

//        new Thread(() -> test.synchronizedGet(Thread.currentThread())).start();
//        new Thread(() -> test.synchronizedGet(Thread.currentThread())).start();

        new Thread(() -> test.readLockget(Thread.currentThread())).start();
        new Thread(() -> test.readLockget(Thread.currentThread())).start();

    }

    public synchronized void synchronizedGet(Thread thread) {
        long start = System.currentTimeMillis();
        while (System.currentTimeMillis() - start <= 1) {
            System.out.println(thread.getName() + "正在进行读操作");
        }
        System.out.println(thread.getName() + "读操作完毕");
    }

    public void readLockget(Thread thread) {
        rwl.readLock().lock();
        try {
            long start = System.currentTimeMillis();

            while (System.currentTimeMillis() - start <= 1) {
                System.out.println(thread.getName() + "正在进行读操作");
            }
            System.out.println(thread.getName() + "读操作完毕");
        } finally {
            rwl.readLock().unlock();
        }
    }
}
